import router from "@/router";
import store from "@/store";
import AccessEnum from "@/access/accessEnum";
import checkAccess from "@/access/checkAccess";

/**
 * 全局权限管理
 */
router.beforeEach(async (to, from, next) => {
  //之前登录过，有session在浏览器中，刷新页面要实现自动登录
  if (store.state.user.userInfo.userRole === AccessEnum.NOT_LOGIN) {
    await store.dispatch("getLoginUser");
  }
  const userInfo = store.state.user.userInfo;
  //要跳转的页面需要登录
  const needAccess = (to.meta?.access as string) ?? AccessEnum.NOT_LOGIN;
  if (needAccess !== AccessEnum.NOT_LOGIN) {
    //没登陆则跳转到登录页
    if (userInfo.userRole === AccessEnum.NOT_LOGIN) {
      next("/login");
      return;
    }
    //登录了则校验权限
    if (!checkAccess(userInfo, needAccess)) {
      next("/noAuth");
      return;
    }
  }
  next();
});
